package cn.com.mall.product.service.impl;

import cn.com.mall.product.vo.Catelog2Vo;
import cn.com.mall.product.vo.Catelog3Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.com.mall.common.utils.PageUtils;
import cn.com.mall.common.utils.Query;

import cn.com.mall.product.dao.CategoryDao;
import cn.com.mall.product.entity.CategoryEntity;
import cn.com.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询出来所有分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);


        //组装成父子的树形结构
        List<CategoryEntity> level1Menus = categoryEntityList.stream().filter(
                (categoryEntity) -> categoryEntity.getParentCid() == 0
        ).map(
                (menu) -> {
                    //获取所有的子分类（递归调用）
                    menu.setChildren(getChildrenMenu(menu, categoryEntityList));
                    return menu;
                }
        ).sorted(
                (m1, m2) -> (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort())
        ).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMeunByIds(List<Long> asList) {
        //TODO 需要先检查当前要删除的菜单是否被被人地方引用


        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();

//        CategoryEntity byId = this.getById(catelogId);
        List<Long> parentPath=findParentPath(catelogId,paths);//将结果倒叙一下
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);

    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));

        return categoryEntityList;
    }

    @Override
    @Cacheable(value = "category",key = "'getCategoryJson'")
    public Map<String, List<Catelog2Vo>> getCategoryJson() {
        log.error("开始查询。。。。。getCategoryJson");

        //查询出1级分类
        List<CategoryEntity> category1EntityList = getLevel1Categorys();

        if(category1EntityList==null){
            return null;
        }

        Map<String, List<Catelog2Vo>> parent_cid = category1EntityList.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            Long level1CatlogId = v.getCatId();
            List<Catelog2Vo> catelog2Vos = null;
            //查询出来2级分类的信息
            QueryWrapper<CategoryEntity> categoryEntityQueryWrapper = new QueryWrapper<CategoryEntity>().eq("parent_cid", level1CatlogId);
            List<CategoryEntity> categoryEntityList = baseMapper.selectList(categoryEntityQueryWrapper);

            if (categoryEntityList != null) {
                catelog2Vos = categoryEntityList.stream().map(
                        item -> new Catelog2Vo(level1CatlogId.toString(), item.getCatId().toString(), item.getName(), null)

                ).collect(Collectors.toList());

                if (catelog2Vos != null) {

                    catelog2Vos= catelog2Vos.stream().map(item->{
                        item.getCatalog1Id();

                        List<CategoryEntity> categoryEntityList3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", item.getId()));

                        List<Catelog3Vo> collect3 = categoryEntityList3.stream().map(item3 ->

                                new Catelog3Vo(item3.getParentCid().toString(), item3.getCatId().toString(), item3.getName())

                        ).collect(Collectors.toList());

                        item.setCatalog3List(collect3);
                        return item;


                    }).collect(Collectors.toList());

                }
            }
            return catelog2Vos;
        }));

        return parent_cid;
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if(entity.getParentCid()!=0){
            this.findParentPath(entity.getParentCid(),paths);
        }
        return paths;
    }

    /**
     * 递归的获取菜单
     *
     * @param root
     * @param categoryEntityList
     * @return
     */
    private List<CategoryEntity> getChildrenMenu(CategoryEntity root, List<CategoryEntity> categoryEntityList) {

        return categoryEntityList.stream().filter(
                menu ->  menu.getParentCid().equals(root.getCatId())

        ).map(
                (m) -> {

                    m.setChildren(getChildrenMenu(m, categoryEntityList));
                    return m;
                }
        ).sorted(
                (m1, m2) -> (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort())
        ).collect(Collectors.toList());


    }


}